"""
配置管理API路由
"""

from fastapi import APIRouter, HTTPException
from typing import Dict, Any, Optional
from pydantic import BaseModel

from ..core.config_manager import config_manager
from ..core.logger import app_logger

router = APIRouter()


class ConfigUpdateRequest(BaseModel):
    """配置更新请求模型"""
    key: str
    value: Any


class ConfigBatchUpdateRequest(BaseModel):
    """批量配置更新请求模型"""
    updates: Dict[str, Any]


class ConfigImportRequest(BaseModel):
    """配置导入请求模型"""
    config_data: str
    format: str = "yaml"  # yaml or json


@router.get("/", summary="获取所有配置")
async def get_all_config():
    """获取完整的配置信息"""
    
    try:
        return {
            "status": "success",
            "data": config_manager.config_data
        }
    except Exception as e:
        app_logger.error(f"获取配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@router.get("/key/{config_key:path}", summary="获取指定配置项")
async def get_config_by_key(config_key: str):
    """获取指定的配置项"""
    
    try:
        value = config_manager.get(config_key)
        
        if value is None:
            raise HTTPException(status_code=404, detail=f"配置项不存在: {config_key}")
        
        return {
            "status": "success",
            "key": config_key,
            "value": value
        }
    except HTTPException:
        raise
    except Exception as e:
        app_logger.error(f"获取配置项失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取配置项失败: {str(e)}")


@router.post("/key", summary="设置配置项")
async def set_config(request: ConfigUpdateRequest):
    """设置单个配置项"""
    
    try:
        success = config_manager.set(request.key, request.value)
        
        if not success:
            raise HTTPException(status_code=500, detail="设置配置项失败")
        
        app_logger.info(f"配置项设置成功: {request.key} = {request.value}")
        
        return {
            "status": "success",
            "message": "配置项设置成功",
            "key": request.key,
            "value": request.value
        }
    except HTTPException:
        raise
    except Exception as e:
        app_logger.error(f"设置配置项失败: {e}")
        raise HTTPException(status_code=500, detail=f"设置配置项失败: {str(e)}")


@router.post("/batch", summary="批量更新配置")
async def batch_update_config(request: ConfigBatchUpdateRequest):
    """批量更新多个配置项"""
    
    try:
        success = config_manager.update(request.updates)
        
        if not success:
            raise HTTPException(status_code=500, detail="批量更新配置失败")
        
        app_logger.info(f"批量更新配置成功: {len(request.updates)} 个配置项")
        
        return {
            "status": "success",
            "message": f"批量更新 {len(request.updates)} 个配置项成功",
            "updated_count": len(request.updates)
        }
    except HTTPException:
        raise
    except Exception as e:
        app_logger.error(f"批量更新配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"批量更新配置失败: {str(e)}")


@router.post("/save", summary="保存配置到文件")
async def save_config():
    """保存当前配置到配置文件"""
    
    try:
        success = config_manager.save_config()
        
        if not success:
            raise HTTPException(status_code=500, detail="保存配置文件失败")
        
        return {
            "status": "success",
            "message": "配置文件保存成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        app_logger.error(f"保存配置文件失败: {e}")
        raise HTTPException(status_code=500, detail=f"保存配置文件失败: {str(e)}")


@router.post("/reload", summary="重新加载配置")
async def reload_config():
    """从配置文件重新加载配置"""
    
    try:
        config_manager.load_config()
        
        return {
            "status": "success",
            "message": "配置重新加载成功"
        }
    except Exception as e:
        app_logger.error(f"重新加载配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"重新加载配置失败: {str(e)}")


@router.get("/export", summary="导出配置")
async def export_config(format: str = "yaml"):
    """导出配置文件"""
    
    try:
        if format not in ["yaml", "json"]:
            raise HTTPException(status_code=400, detail="不支持的导出格式，支持: yaml, json")
        
        config_str = config_manager.export_config(format)
        
        if not config_str:
            raise HTTPException(status_code=500, detail="导出配置失败")
        
        return {
            "status": "success",
            "format": format,
            "data": config_str
        }
    except HTTPException:
        raise
    except Exception as e:
        app_logger.error(f"导出配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"导出配置失败: {str(e)}")


@router.post("/import", summary="导入配置")
async def import_config(request: ConfigImportRequest):
    """导入配置文件"""
    
    try:
        if request.format not in ["yaml", "json"]:
            raise HTTPException(status_code=400, detail="不支持的导入格式，支持: yaml, json")
        
        success = config_manager.import_config(request.config_data, request.format)
        
        if not success:
            raise HTTPException(status_code=500, detail="导入配置失败")
        
        app_logger.info("配置导入成功")
        
        return {
            "status": "success",
            "message": "配置导入成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        app_logger.error(f"导入配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"导入配置失败: {str(e)}")


@router.get("/platforms", summary="获取平台配置")
async def get_platforms_config():
    """获取所有平台的配置信息"""
    
    try:
        platforms = ["weibo", "twitter", "wechat"]
        platform_configs = {}
        
        for platform in platforms:
            platform_config = config_manager.get_platform_config(platform)
            platform_configs[platform] = {
                "enabled": platform_config.enabled,
                "max_length": platform_config.max_length,
                "rate_limit": platform_config.rate_limit
            }
        
        return {
            "status": "success",
            "data": platform_configs
        }
    except Exception as e:
        app_logger.error(f"获取平台配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取平台配置失败: {str(e)}")


@router.get("/ai", summary="获取AI配置")
async def get_ai_config():
    """获取AI配置信息"""
    
    try:
        ai_config = config_manager.get_ai_config()
        
        return {
            "status": "success",
            "data": {
                "provider": ai_config.provider,
                "openai": {
                    "model": ai_config.openai_model,
                    "max_tokens": ai_config.openai_max_tokens,
                    "temperature": ai_config.openai_temperature,
                    "timeout": ai_config.openai_timeout
                },
                "claude": {
                    "model": ai_config.claude_model,
                    "max_tokens": ai_config.claude_max_tokens,
                    "timeout": ai_config.claude_timeout
                }
            }
        }
    except Exception as e:
        app_logger.error(f"获取AI配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取AI配置失败: {str(e)}")


@router.get("/scheduler", summary="获取调度器配置")
async def get_scheduler_config():
    """获取调度器配置信息"""
    
    try:
        scheduler_config = config_manager.get_scheduler_config()
        
        return {
            "status": "success",
            "data": {
                "enabled": scheduler_config.enabled,
                "timezone": scheduler_config.timezone,
                "max_workers": scheduler_config.max_workers,
                "schedules": config_manager.get("scheduler.schedules", {})
            }
        }
    except Exception as e:
        app_logger.error(f"获取调度器配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取调度器配置失败: {str(e)}")


@router.get("/status", summary="获取配置状态")
async def get_config_status():
    """获取配置管理器状态信息"""
    
    try:
        return {
            "status": "success",
            "data": {
                "config_file": str(config_manager.config_path),
                "file_exists": config_manager.config_path.exists(),
                "mock_mode": config_manager.is_mock_mode(),
                "debug_mode": config_manager.is_debug_mode(),
                "total_config_items": len(str(config_manager.config_data).split(':')),
                "available_styles": config_manager.get_content_styles()
            }
        }
    except Exception as e:
        app_logger.error(f"获取配置状态失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取配置状态失败: {str(e)}")